﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CTThrottling.Common;
using StackExchange.Redis;

namespace ThrottlingWebTest.Filter
{
    public class ThrottlingLimitAttribute: ActionFilterAttribute
    {
        #region
        private readonly RedisStackExchangeHelper _redis = new RedisStackExchangeHelper();
        private IDatabase _db = null;
        #endregion

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _db = _redis.GetDatabase();
            var clientIp = WebHelper.GetClientIp();

            #region Ip单位时间访问次数限制

            //var aa = Context.Request.Url.AbsoluteUri;
            var times = _db.StringIncrement(clientIp);
            if (1 == times)
            {
                _db.KeyExpire(clientIp, TimeSpan.FromSeconds(60));
            }
            if (times > 3)
            {
                filterContext.RequestContext.HttpContext.Response.Redirect("~/StaticHtml/test.html");
                var liveTime = _db.KeyTimeToLive(clientIp);
                if (liveTime == null)
                {
                    _db.KeyExpire(clientIp, TimeSpan.FromSeconds(60));
                }
            }
            #endregion
        }
    }
}